package work.linruchang.oauthresourceproject.config.interceptor;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import work.linruchang.oauthresourceproject.bean.ThirdSystemInfo;
import work.linruchang.oauthresourceproject.config.oauth.ThreadLocalRequestInfo;
import work.linruchang.oauthresourceproject.service.ThirdSystemInfoService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Basic认证
 * 第三方客户端获取token
 * @author LinRuChang
 * @version 1.0
 * @date 2022/08/04
 * @since 1.8
 **/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class ClientBasicAuthInterceptor implements HandlerInterceptor {

    @Autowired
    ThirdSystemInfoService thirdSystemInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean authStatusFlag = false;
        String authorization = request.getHeader("Authorization");
        String authType = null;
        String authInfoCredentials = null;
        String clientId = request.getParameter("client_id");
        String clientSecret = request.getParameter("client_secret");
        List<String> authorizationInfos = StrUtil.splitTrim(authorization, StrUtil.SPACE);
        if(CollUtil.size(authorizationInfos) == 2) {
            authType = authorizationInfos.get(0);
            authInfoCredentials = authorizationInfos.get(1);
            if (StrUtil.isNotBlank(authInfoCredentials)) {
                if (StrUtil.equalsAnyIgnoreCase(authType, "BASIC")) {
                    String authInfo = Base64.decodeStr(authInfoCredentials);
                    List<String> authInfos = StrUtil.splitTrim(authInfo, StrUtil.COLON);
                    clientId = CollUtil.size(authInfos) >= 2 ? authInfos.get(0) : null;
                    clientSecret =  CollUtil.size(authInfos) >= 2 ? authInfos.get(1) : null;
                }
            }
        }

        //这里自行获取数据库中的用户、密码信息进行校验是否正确
        ThirdSystemInfo thirdSystemInfo = getThirdSystemInfo(clientId);
        if(thirdSystemInfo != null && StrUtil.equals(clientSecret,thirdSystemInfo.getClientSecret())) {
            authStatusFlag = true;
        }


        //认证失败
        if (!authStatusFlag) {
            response.setHeader("WWW-Authenticate",StrUtil.format("{} realm=\"rights of administrators\"", StrUtil.blankToDefault(authType,"BASIC")));
            response.setStatus(401);
            response.setHeader("Content-Type","text/plain;charset=utf-8");
            response.getWriter().write("认证失败：请输入合法的clientId、clientSecret信息");
            return false;
        }

        //添加cookie信息给用户 == 当前用户名
        if(!StrUtil.containsIgnoreCase(request.getRequestURI(),"logout")) {
            Cookie userNameCookie = new Cookie("userName", clientId);
            userNameCookie.setPath("/");
            response.addCookie(userNameCookie);

            Cookie userNameDescCookie = new Cookie("userNameDesc", "管理员");
            userNameDescCookie.setPath("/");
            response.addCookie(userNameDescCookie);
        }
        ThreadLocalRequestInfo.setClientId(clientId);
        ThreadLocalRequestInfo.setClientSecret(clientSecret);


        return authStatusFlag;
    }

    public ThirdSystemInfo getThirdSystemInfo(String clientId) {
        return thirdSystemInfoService.getOne(Wrappers.lambdaQuery(ThirdSystemInfo.builder().clientId(clientId).build()), false);
    }
}
